//FastClick.attach(document.body);
var Vote = {
	lng : "",
	lat : "",
	posStatus : "0",	//定位状态 0.未开始定位, 1.正在定位, 2.定位成功, 3.定位失败
	getCurrentPosition : function(callbackFn){
		var that = this;
		that.posStatus = "1";
		if (navigator.geolocation){
			navigator.geolocation.getCurrentPosition(function(position){
				that.lng = position.coords.longitude;
				that.lat = position.coords.latitude;
				that.posStatus = "2";
				callbackFn.call(this);
			},function(error){
				that.posStatus = "3";
				callbackFn.call(this);
			},{
				enableHighAcuracy: true,
				timeout: 5000,
				maximumAge: 3000
			});
		}
	},
	fixEmptyValue : function(v){
		if(v == null || v == ""){
			v = "无"
		}
		return v;
	},
	addJS : function(jsPath, fn){
		var headEle = document.getElementsByTagName("head")[0]; 
		var scriptEle = document.createElement("script");
		scriptEle.setAttribute("type", "text/javascript"); 
		scriptEle.setAttribute("src", jsPath); 
		if(typeof(fn) == "function"){
			scriptEle.onload = fn;
		}
		headEle.appendChild(scriptEle);
	},
	ajax : function(url, data, callback){
		if(typeof(data) == "function"){
			callback = data;
			data = null;
		}
		$.get(url, data, function(responseText){
			var result = $.parseJSON(responseText);
			var status = result["status"];
			if(status == "1"){
				callback.call(this, result);
			}else{
				var errMsg = result["errMsg"];
				alert(errMsg);
			}
		});
	},
	buildMainPage : function(pageInto, pageOut, options){
		var that = this;
		var $page = $("#vote_main");
		
		that.listScroll = that.createScroll("#vote_main div.listContent", function(){
			that.downRefreshList();
		});
		
		var $tab = $(".tab", $page);
		$("ul li", $tab).click(function(e){
			if(!$(this).hasClass("selected")){
				$(this).siblings("li.selected").removeClass("selected");
				$(this).addClass("selected");
				that.resetSearch();
				that.refreshList("tabChange");
			}
		});	
		
		$(".load_more", $page).click(function(){
			that.loadList();
		});
		
		$("form[disabledEnterSubmit]", $page).keydown(function(event){
			if(event.keyCode == 13){return false;}
		});
		var $searchBtn = $(".listSearch .btn", $page);
		var $searchKey = $(".listSearch input", $page);
		$searchBtn.click(function(){
			that.pushSearchCondition("subject", $searchKey.val());
			that.refreshList();
			$searchKey[0].blur();
		});
		$searchKey.on("input", function(){
			$("#vote_search input[data-fieldname='subject']").val($(this).val());
		}).keyup(function(event){
			if(event.keyCode == 13){
				$searchBtn.triggerHandler("click");
			}
		});
		$("ul li", $tab).eq(0).triggerHandler("click");
	},
	listPageNo : 0,
	listPageSize : 20,
	listScroll : null,
	refreshListTimestamp : null,
	searchCondition : {},
	pushSearchCondition : function(name, value){
		this.searchCondition[name] = value;
	},
	clearSearchCondition : function(){
		this.searchCondition = {};
	},
	refreshListScroll : function(){
		var that = this;
		if(that.listScroll){
			that.listScroll.refresh();
		}
	},
	createScroll : function(selector, refreshCallback){
		var $wrap = $(selector);
		var $pullDown = $(".pullDown", $wrap);
		var pullDownEl = null;
		var pullDownOffset = 0;
		if($pullDown.length > 0){
			$pullDown.show();
			pullDownEl = $pullDown[0];
			pullDownOffset = pullDownEl.offsetHeight;
		}
		var _scroll = new IScroll(selector, {
			mouseWheel: true,
			topOffset: pullDownOffset,
			preventDefault: false,
			scrollbars: "custom",
			fadeScrollbars: true
		});
		
		if(pullDownEl != null){
			_scroll.on('refresh', function () {
				if (pullDownEl.className.match('scroll_loading')) {
					pullDownEl.className = 'pullDown';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉可以刷新';
				}
			});
			
			_scroll.on('scrollMove', function () {
				if (this.y > 50 && !pullDownEl.className.match('flip')) {
					pullDownEl.className = 'pullDown flip';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放立即刷新';
					this.minScrollY = 0;
				} else if (this.y < 50 && pullDownEl.className.match('flip')) {
					pullDownEl.className = 'pullDown';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉可以刷新';
					this.minScrollY = -pullDownOffset;
				}
			});
			
			_scroll.on('scrollEnd', function () {
				if (pullDownEl.className.match('flip')) {
					pullDownEl.className = 'pullDown scroll_loading';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '正在刷新...';
					if(typeof(refreshCallback) == "function"){
						refreshCallback.call(this);
					}
				}	
			});
		}
		_scroll.refresh();
		$wrap.on("touchmove", function (e) { e.preventDefault(); });
		return _scroll;
	},
	refreshList : function(_action){
		var that = this;
		that.listPageNo = 0;
		var $page = $("#vote_main");
		$(".content", $page).addClass("list_refreshing");
		setTimeout(function(){that.refreshListScroll();}, 300);
		
		that.loadList(true, _action);
	},
	downRefreshList : function(){
		var that = this;
		that.listPageNo = 0;
		that.loadList(true);
	},
	formatDate : function(dateStr){
		return dateStr.replace("-","/").replace("-","/")
		.replace("/0","/").replace("/0","/");
	},
	loadList : function(unShowloading, _action){
		var that = this;
		
		var timestamp = (new Date()).valueOf();	//时间戳
		that.refreshListTimestamp = timestamp;
		
		that.listPageNo++;
		var url = "/mobilemode/apps/e-cology/vote/voteAction.jsp?operate=getVotingList";
		var $page = $("#vote_main");
		var $currTab = $(".tab ul li.selected", $page);
		var filter = $currTab.attr("data-filter") || "";
		url = url + filter;
		var $loading = $(".crm_loading", $page);
		if(unShowloading != true){
			$loading.show();			
		}
		var $load_more = $(".load_more", $page);
		$load_more.hide();
		var dataUrl = $currTab.attr("data-url") || "";
		that.ajax(url, that.searchCondition, function(result){
			if(timestamp != that.refreshListTimestamp){
				return;
			}
			
			$loading.hide();
			
			var $list = $(".list", $page);
			if(that.listPageNo == 1){
				$list.find("*").remove();
				that.refreshListScroll();
			}
			var datas = result["voteList"];
			var statusText = {"0":"创建", "1":"进行", "2":"结束", "3":"审批"};
			var html = "";
			//{"voteList":[{"id":"562","subject":"移动测试调查0810","begindate":"2016-08-09","begintime":"00:00","enddate":"2016-08-12","endtime":"08:33","desc":"","status":"1","votingcount":""}],"status":"1","msg":""}
			for(var i = 0; i < datas.length; i++){
				var d = datas[i];
				var statusHtml = "";
				var status = d["status"];
				if(status != ""){
					statusHtml = "<div class=\"flag flag"+d["status"]+"\">"+statusText[status]+"</div>";
				}
				
				var timeHtml = "开始时间：" + d["begindate"] + " " + d["begintime"];
				var timeHtml2 = "结束时间：" + d["enddate"] + " " + d["endtime"];
				
				html += "<li>"
					+"<a href=\""+dataUrl+"\" data-formdata=\"id="+d["id"]+"\" data-reload=\"true\">"
						+statusHtml
						+"<div class=\"title\">"+d["subject"]+"</div>"
						+"<div>"+timeHtml+"</div>"
						+"<div>"+timeHtml2+"</div>"
					+"</a>"
				+"</li>";
			}
			$list.append(html);
			
			var totalSize = datas.length;
			if(totalSize <= 0){
				$(".no_data", $page).show();
			}else{
				$(".no_data", $page).hide();
			}
			/*
			var totalPageCount;
			if(totalSize % that.listPageSize == 0){
				totalPageCount = totalSize / that.listPageSize;
			}else{
				totalPageCount = parseInt(totalSize / that.listPageSize) + 1;
			}
			if(that.listPageNo >= totalPageCount){
				$load_more.hide();
			}else{
				$load_more.show();
			}
			*/
			$(".content", $page).removeClass("list_refreshing");
			setTimeout(function(){that.refreshListScroll();}, 300);
			that.refreshListScroll();
		});
	},
	buildSearchPage : function(pageInto, pageOut, options){
		var that = this;
		var $page = $("#vote_search");
		$(".clear-btn", $page).click(function(){
			var $field = $(this).parents(".field[data-flag]");
			if($field.length > 0){
				var flag = $field.attr("data-flag");
				that.setSearchValue("", "", flag, false);
			}
		});
		
		$(".hori_check", $page).click(function(e){
			if(e.target && e.target.tagName.toLowerCase() == "li"){
				var $this = $(e.target);
				var $realField = $this.parent().siblings("input[data-fieldname]");
				if($this.hasClass("checked")){
					var type = $this.parent().attr("data-type");
					if(type == "CAN_CANCEL"){
						$this.removeClass("checked");
						$realField.val("");
					}
				}else{
					$this.siblings("li.checked").removeClass("checked");
					$this.addClass("checked");
					var v = $this.attr("data-value");
					$realField.val(v);
				}
			}
		});
		
		var currYear = (new Date()).getFullYear();	
		var opt={};
		opt.date = {preset : 'date', dateFormat : "yy-mm-dd"};
		opt.defa = {
			theme: 'android-ics light', //皮肤样式
	        display: 'modal', //显示方式 
	        mode: 'scroller', //日期选择模式
			lang:'zh',
	        startYear:currYear - 100, //开始年份
	        endYear:currYear + 1 //结束年份
		};
		
		var optCurr = $.extend(opt['date'], opt['defa']);
		$("input[data-type='date']", $page).change(function(){
			if(this.value != ""){
				$(this).closest(".field").addClass("hasValue");
			}
		}).mobiscroll(optCurr).date(optCurr);
			
		$("form[disabledEnterSubmit]", $page).keydown(function(event){
			if(event.keyCode == 13){return false;}
		});
		
		var $searchBtn = $(".header .right", $page);
		var $searchKey = $("input[data-fieldname='subject']", $page);
		$searchBtn.click(function(){
			$("input[data-fieldname]", $page).each(function(){
				var v = $(this).val();
				if(v == null){
					v = "";
				}
				var name = $(this).attr("data-fieldname");
				that.pushSearchCondition(name, v);
			});
			that.refreshList();
			$searchKey[0].blur();
			history.go(-1);
		});
		
		$searchKey.on("input", function(){
			$("#vote_main .listSearch input").val($(this).val());
		}).keyup(function(event){
			if(event.keyCode == 13){
				$searchBtn.triggerHandler("click");
			}
		});
	},
	setSearchValue : function(value, text, flag, isBack){
		var $field = $("#vote_search .field[data-flag='"+flag+"']");
		var $realField = $("input[data-fieldname='"+flag+"']", $field);
		$realField.val(value);
		
		if(value == ""){
			$field.removeClass("hasValue");
		}else{
			$field.addClass("hasValue");
		}
		
		var $more = $(".more", $field);
		if($more.length > 0){
			$(".text", $more).html(text);
		}
		
		var $horiCheck = $realField.siblings(".hori_check");
		if($horiCheck.length > 0){
			$("li", $horiCheck).removeClass("checked");	
			if(value != ""){
				$("li[data-value='"+value+"']", $horiCheck).addClass("checked");
			}
		}
		
		if(isBack == true){
			history.go(-1);
		}
	},
	resetSearch : function(){
		var that = this;
		var $page = $("#vote_search");
		$(".field[data-flag]", $page).each(function(){
			var flag = $(this).attr("data-flag");
			var v = "";
			that.setSearchValue(v, "", flag, false);
		});
		var $searchKey = $("#vote_main .listSearch input");
		$searchKey.val("");
		that.clearSearchCondition();
	},
	showMsg : function(msgStr){
		$("#msg").html(msgStr).show();
	},
	hideMsg : function(){
		$("#msg").hide();
	}
};
Mobilebone.rootTransition = Vote;
Mobilebone.evalScript = true;